package com.llp.declaresystem.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.llp.declaresystem.domain.Result;
import com.llp.declaresystem.domain.entity.AdminExpertView;
import com.llp.declaresystem.domain.entity.Expert;
import com.llp.declaresystem.domain.entity.ProjectCategory;
import com.llp.declaresystem.service.ExpertService;
import com.llp.declaresystem.service.ProjectCategoryService;
import com.llp.declaresystem.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author llp
 * {@code @date} 2022年11月26日8:07
 * admin对专家信息页进行管理
 */
@RestController
@RequestMapping("/api/admin")
public class ExpertMessageController {
    @Autowired
    ExpertService expertService;
    @Autowired
    UserService userService;
    @Autowired
    ProjectCategoryService projectCategoryService;

    //获取专家信息列表
    @RequestMapping(value = "/showExperts", method = RequestMethod.GET)
    public Result showExperts() {
        List<Expert> list = expertService.list();
        if (list != null)
            return new Result<>(200, "返回专家信息", list);
        else
            return new Result<>(405, "获取专家信息失败", null);

    }
    //获取专家的expertid以及name
    @RequestMapping("/getExpertView")
    public Result getExpertView()
    {
        List<Expert> list = expertService.list();
        List<AdminExpertView> views=new ArrayList<>();
        list.forEach((expert)->{
            AdminExpertView adminExpertView = new AdminExpertView(expert.getExpertid(),expert.getName());
            views.add(adminExpertView);
        });
        return new Result<>(200,"获取仅含expertid和name的专家视图",views);

    }

    //更新专家信息
    @RequestMapping("/updateExpert")
    public Result updateExpert(@RequestBody Expert expert) {

        boolean b = expertService.saveOrUpdate(expert);
        if (b) return new Result<>(200, "修改成功", null);
        else return new Result<>(405, "修改失败", null);
    }

    //删除专家信息
    @RequestMapping(value = "/deleteExpert",method = RequestMethod.POST)
    public Result deleteExpert(@RequestBody Map<String,Integer> map) {
        boolean removeExpert=false;
        boolean removeUser =false;
        Integer uid=map.get("uid");
        Integer expertid=map.get("expertid");
        //先删除projectcategory的记录
        QueryWrapper<ProjectCategory> wrapper=new QueryWrapper<>();
        wrapper.eq("expertid",expertid);
        projectCategoryService.remove(wrapper);
         //再删除专家表，再删除user表
        //专家表和用户表同时有数据才能进行删除
        if (uid != null && expertid != null) {
            removeExpert = expertService.removeById(expertid);
            removeUser = userService.removeById(uid);
        }
        if(removeUser&&removeUser)
            return new Result<>(200,"删除成功",null);
        else return new Result<>(405,"删除失败",null);


    }

}
